package com.dinfo.oec.daemon.load;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class ByteClassLoader extends ClassLoader {

	
//	private String rootDir;
	
	private byte[] codes;
	
	public ByteClassLoader(String rootDir) {
		super();
//		this.rootDir = rootDir;
	}
	
	public void setCodes(byte[] codes)
	{
		this.codes = codes;
	}
	

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
	
		Class<?> c = findLoadedClass(name);
		if(c!=null)
		{
			return c;
		}else{
			ClassLoader parent = this.getParent();
			try {
				c =  parent.loadClass(name);
			} catch (Exception e) {
			}
			
			if(c!=null)
			{
				return c;
			}else{
				byte[] classData = this.codes;
				if(classData == null)
				{
					throw new ClassNotFoundException();
				}else{
					c = defineClass(name, classData, 0 , classData.length);
				}
			}
			
		}
		return c;
	}
	
	
//	private byte[] getClassData(String name) {
//		String path  =  rootDir+"/" +name.replace('.','/')+".class";
//		InputStream is = null;
//		ByteArrayOutputStream bos = new ByteArrayOutputStream();
//		
//		try {
//			is = new FileInputStream(path);
//			byte[] buffer = new byte[1024];
//			int temp = 0;
//			while((temp=is.read(buffer)) != -1)
//			{
//				bos.write(buffer, 0, temp);
//			}
//			return bos.toByteArray();
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return null;
//	}

}
